import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import { useState } from "react";
import HeaderInfo from "../headerInfo";
import PublishDrawer from "../publishDrawer";
import { useSelector, useDispatch } from "react-redux";
import richTextEditorLess from "./index.module.less";
import { Input } from "antd";
import { setOpen } from "@/store/modules/publishArticle";
import { ImportOutlined } from "@ant-design/icons";
import { InsertFnType } from "./util/type";
import { EditorUploadFileApi } from "@/http/api/upload";

function RichTextEditor() {
  //富文本组件内容
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  // 编辑器内容
  const [html, setHtml] = useState("");

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {};

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: "请输入正文...",
    MENU_CONF: {
      uploadImage: {
        async customUpload(file: any, insertFn: any) {
          let formData = new FormData(); //创建格式
          console.log(2222, file);
          formData.append("file", file);
          const res: any = await EditorUploadFileApi(formData);
          console.log("上传图片结果", res);
          insertFn(res.data.url, res.data.alt, res.data.href);
        },
      },
    },
  };
  const dispatch = useDispatch();

  const [Title, setTitle] = useState("");

  const handleInputChange = (e: any) => {
    setTitle(e.target.value);
  };

  return (
    <>
      <div className={richTextEditorLess.richTextEditor_content}>
        <HeaderInfo releaseSend={() => dispatch(setOpen(true))} />
        <div className="richText_title_input">
          <Input
            maxLength={100}
            className="input"
            value={Title}
            placeholder="输入标题..."
            onChange={handleInputChange}
          />
        </div>
        <div className="rich_bf">
          <Toolbar
            editor={editor}
            defaultConfig={toolbarConfig}
            mode="default"
            style={{ borderBottom: "1px solid #ccc" }}
          />
          <Editor
            defaultConfig={editorConfig}
            value={html}
            onCreated={setEditor}
            onChange={(editor) => setHtml(editor.getHtml())}
            mode="default"
            style={{ height: "100%", overflowY: "hidden" }}
          />
        </div>
      </div>
      <PublishDrawer Title={Title} Content={html} />
    </>
  );
}

export default RichTextEditor;
